package com.fuyun.microservice.connect.impl;


import com.fuyun.microservice.connect.SessionStore;
import com.fuyun.microservice.connect.pojo.ClientEndpoint;
import io.netty.channel.Channel;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;

@Service
public class DefaultSessionStoreImpl implements SessionStore {
    private static ConcurrentMap<Channel,ClientEndpoint> CHANNELS=new ConcurrentHashMap();

    @Override
    public List<ClientEndpoint> all() {
        return CHANNELS.values().stream().collect(Collectors.toList());
    }

    @Override
    public void add(Channel channel,ClientEndpoint clientEndpoint) {
        CHANNELS.put(channel,clientEndpoint);
    }

    @Override
    public void remove(Channel channel) {
        CHANNELS.remove(channel);
    }

    @Override
    public ClientEndpoint getClient(Channel channel) {
         return CHANNELS.get(channel);
    }


    @Override
    public Channel getChannel(int clientId){
        for(Map.Entry<Channel,ClientEndpoint> entry: CHANNELS.entrySet()){
            if(entry.getValue().getClientId()==clientId){
                return entry.getKey();
            }
        }

        return null;
    }
}
